import { creepRoleEnum, creepRuleNameEnum, taskType } from "../../enum";
import { getBodymoduleCount } from "../../tools/tools/creepTool";
import { publishSpawnTask } from "../task/taskManager"
import { creepCount } from "../../config";
import eventManager from "../event/eventManager";
import { eventMap } from "../event/eventMap";
import { objIDToObj } from "../../tools/baseTools";

function _mountController() {
    Object.assign(StructureController.prototype, extension)
}

const extension = {
    name: '控制中心',
    taskPool: [],
    init: function () {
        this.name = this.pos.roomName + this.name
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        objMemory['state'] = {}
        objMemory['state']['needCreep'] = false
    },
    run: function (params = {}) {
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        if (!objMemory.isRuning) {
            if (objMemory.publishTask.length == 0) {
                // 检查自身状态，则根据state各个结果，判断是否发布对应任务,会修改publishTask属性
                this.updateSelfState()
                if (objMemory['state']['needCreep']) pushSpawnUpgraderask(this)
                // 无任务，publishTask未更改为true，则进入休眠状态isRuning更改为true，一段时间后自动唤醒
                objMemory.isRuning = true
                eventManager.add(`当前无任务，${this.name}进入休眠,等待唤醒`, 10, eventMap.objToSleep, { objID: this.id })
            }
        }
    },
    /**检查自身状态，避免出现异常数据 */
    checkSelf: function () {
        let isRuning = false
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        // 避免isRuning进入死循环:
        if (Object.keys(Memory.event).map(eventID => {
            let eventDeta = Memory.event[eventID]
            if (eventDeta['eventMap'] == eventMap.objToSleep.name && eventDeta['params']['objID'] == this.id) {
                isRuning = true
            } else {
                isRuning = isRuning || false
            }
        }))
            objMemory.isRuning = isRuning
        // 避免publishTask出现异常
        if (objMemory.publishTask.length != 0) {
            let publishTaskList = []
            objMemory.publishTask.map(taskID => { if (Memory.rooms[this.pos.roomName]['task']['taskDeta'][taskID]) publishTaskList.push(taskID) })
            objMemory.publishTask = publishTaskList   // 更新发布的任务
        }
    },
    /**更新自身状态 */
    updateSelfState: function () {
        let objMemory = Memory.rooms[this.pos.roomName]['structure'][this.structureType][this.id]
        objMemory['state']['needCreep'] = isAllowpushSpawnUpgraderask(objMemory, creepCount.upgrader[this.level], this.room)
    },
    /**获取任务 */
    getTask: function () {

    }
}

/**推送生产upgrader的任务 */
function pushSpawnUpgraderask(obj) {
    obj = objIDToObj(obj)
    let taskDeta = {
        taskID: '生产upgrader',
        taskType: taskType.spawnCreep,
        publisherID: obj.id,
        roomName: obj.pos.roomName,
        taskParams: {
            room: obj.pos.roomName,
            tag: 'worker',
            role: creepRoleEnum.worker.upgrader,
            rule: creepRuleNameEnum.ruleUpgrader,
            targetID: [obj.id],
            targetPos: obj.pos,
            params: {}
        }
    }
    return publishSpawnTask(taskDeta)
}
// #region 属于controller独有的方法
/**判断是否满足推送任务的条件
 * 1. 当前挂载的creep数量满足配置要求
 * 2. 当前挂载的creep的work部件数量不超过15个
 * @param {*} objMemory 
 * @param {Number} upgrader
 * @returns 
 */
function isAllowpushSpawnUpgraderask(objMemory, upgrader = 3, room) {
    if (objMemory['creeps'].length == 0) return true
    if (objMemory['creeps'].length >= upgrader) return false
    if (room.memory['creeps']['worker']['upgrader'].length >= upgrader) return false
    let creeps = objMemory['creeps'].map(creepName => Game.creeps[creepName])
    if (getBodymoduleCount(creeps)[WORK] >= 15) return false
    return true
}
// #endregion


export default _mountController